package com.group01.utils;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * AES数据加密
 * @Description
 * @Author 翟玉龙
 * @Date 2024/6/16
 */
public class AESUtil {
    private static final String ALGORITHM = "AES";
    private static final String TRANSFORMATION = "AES/CBC/PKCS5Padding";

    private static final SecretKey key;

    static {
        try {
            //key = generateKey();
            // 密钥
            key = convertToSecretKey("jTuQvkGrmmc3FTlSa65PzEvmA1USaW3cn9PR8npCVG8=");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Base64转SecretKey
     * @param aesKey Base64密钥
     * @return SecretKey
     */
    public static SecretKey convertToSecretKey(String aesKey) {
        byte[] decodedKey = Base64.getDecoder().decode(aesKey);
        return new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
    }

    /**
     * 生成随机密钥
     * @return SecretKey
     * @throws Exception e
     */
    public static SecretKey generateKey() throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
        keyGenerator.init(256);
        return keyGenerator.generateKey();
    }

    /**
     * 数据加密
     * @param data 加密数据
     * @return 密文
     * @throws Exception e
     */
    public static String encrypt(String data) throws Exception {
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        byte[] iv = new byte[cipher.getBlockSize()];
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
        cipher.init(Cipher.ENCRYPT_MODE, key, ivParameterSpec);
        byte[] encryptedData = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedData);
    }

    /**
     * 数据解密
     * @param encryptedData 密文
     * @return 解密数据
     * @throws Exception e
     */
    public static String decrypt(String encryptedData) throws Exception {
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        byte[] iv = new byte[cipher.getBlockSize()];
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
        cipher.init(Cipher.DECRYPT_MODE, key, ivParameterSpec);
        byte[] decodedData = Base64.getDecoder().decode(encryptedData);
        byte[] decryptedData = cipher.doFinal(decodedData);
        return new String(decryptedData, StandardCharsets.UTF_8);
    }
}
